package com.pda.xinma.ui.inventory;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.pda.xinma.R;
import com.pda.xinma.adapter.CheckingAdapter;
import com.pda.xinma.adapter.ImageAdapter;
import com.pda.xinma.bean.ImageBean;
import com.pda.xinma.bean.ScanBean;
import com.pda.xinma.bean.ScanResultBean;
import com.pda.xinma.bean.WholePalletInfoBean;
import com.pda.xinma.bean.request.InventoryConfirmRequst;
import com.pda.xinma.bean.request.QRcodeRequest;
import com.pda.xinma.contract.CheckingContract;
import com.pda.xinma.dialog.AffirmDialog;
import com.pda.xinma.net.NetUtils;
import com.pda.xinma.presenter.CheckingPresenter;
import com.pda.xinma.view.ScanButView;
import com.wangshen.base.app.AppActivityKey;
import com.wangshen.base.config.StringKey;
import com.wangshen.base.glide.GlideEngine;
import com.wangshen.base.net.bean.BaseAppEntity;
import com.wangshen.base.net.bean.ImageEntity;
import com.wangshen.base.ui.mvp.base.ui.BaseMvpFragment;
import com.wangshen.base.util.SharedPreferencesUtil;
import com.wangshen.base.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;


public class CheckingFragment extends BaseMvpFragment<CheckingPresenter> implements CheckingContract.View {
    @BindView(R.id.tv_articleId)
    TextView tvArticleId;
    @BindView(R.id.tv_articleName)
    TextView tvArticleName;
    @BindView(R.id.tv_storageBin)
    TextView tvStorageBin;
    @BindView(R.id.tv_stockNum)
    TextView tvStockNum;
    @BindView(R.id.rv_image)
    RecyclerView rvImage;
    @BindView(R.id.tv_add)
    ScanButView tvAdd;
    @BindView(R.id.tv_back_storage)
    TextView tvBackStorage;
    @BindView(R.id.tv_container)
    TextView tvContainer;
    @BindView(R.id.tv_entryNo)
    TextView tvEntryNo;
    @BindView(R.id.tv_thirdOrderNo)
    TextView tvThirdOrderNo;
    @BindView(R.id.ll7)
    LinearLayout ll7;

    @BindView(R.id.et_actualStockNum)
    EditText etActualStockNum;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.tv_model)
    TextView tvModel;
    @BindView(R.id.tv_grade)
    TextView tvGrade;
    @BindView(R.id.tv_inverntory)
    TextView tvInverntory;
    @BindView(R.id.tv_detail)
    TextView tvDetail;

    private String taskResultId;
    ImageAdapter imageAdapter;
    private List<ImageBean> imageBeans = new ArrayList<>();
    private String taskNo;
    CheckingAdapter checkingAdapter;

    public CheckingFragment() {
    }

    public CheckingFragment(String taskNo) {
        this.taskNo = taskNo;
    }

    @Override
    public CheckingPresenter getPresenter() {
        return new CheckingPresenter();
    }

    @Override
    public int getViewId() {
        return R.layout.fragment_checking;
    }

    @Override
    public void initView() {
        // presenter.getWholePalletInfo(taskResultId);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        rvImage.setLayoutManager(layoutManager);
        imageBeans.add(new ImageBean(""));
        imageAdapter = new ImageAdapter(R.layout.item_image, imageBeans);
        rvImage.setAdapter(imageAdapter);
        checkingAdapter = new CheckingAdapter(R.layout.item_checking, new ArrayList<>());
        rvList.setAdapter(checkingAdapter);
    }

    @Override
    public void initLinsenterner() {

        imageAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.iv_image) {
                    if (TextUtils.isEmpty(imageAdapter.getData().get(position).getPath())) {
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())
                                .imageEngine(GlideEngine.createGlideEngine())
                                .maxSelectNum(1)
                                .minSelectNum(1)
                                .isCompress(true)
                                .compressQuality(30)
                                .synOrAsy(true)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                }
                if (view.getId() == R.id.iv_delete) {
                    imageBeans.remove(position);
                    if (imageBeans.size() == 2) {
                        boolean is = false;
                        for (ImageBean bean : imageBeans) {
                            if (TextUtils.isEmpty(bean.getPath())) {
                                is = true;
                            }
                        }
                        if (is) {
                            imageAdapter.notifyDataSetChanged();
                            return;
                        }
                        imageBeans.add(0, new ImageBean(""));
                    }
                    imageAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        tvAdd.setScanCallBack(new ScanButView.ScanCallBack() {
            @Override
            public void callBack(ScanBean scanBean) {
                if (scanBean.getCode().contains("order")) {
                    if (TextUtils.isEmpty(tvContainer.getText().toString())) {
                        showMessage("请先扫接驳位");
                        return;
                    }
                    if (wholePalletInfoBean == null){
                        showMessage("请扫正确的接驳位");
                        return;
                    }
                    int lenth = scanBean.getCode().indexOf("A");
                    String order = scanBean.getCode().substring(lenth + 1);
                    for (WholePalletInfoBean.DetailsBean detailsBean : wholePalletInfoBean.getDetails()) {
                        if (order.equals(detailsBean.getProOrderNo())) {
                            taskResultId = detailsBean.getTaskResultId();
                            tvArticleId.setText(detailsBean.getArticleId());
                            tvArticleName.setText(detailsBean.getArticleName());
                            tvModel.setText(detailsBean.getModel());
                            tvGrade.setText(detailsBean.getGrade());
                            tvEntryNo.setText(detailsBean.getProOrderNo());
                            tvThirdOrderNo.setText(detailsBean.getProcessName());
                            tvStockNum.setText(detailsBean.getStockNum());
                            etActualStockNum.setText(detailsBean.getActualStockNum() + "");
                        }
                    }
                    if (TextUtils.isEmpty(taskResultId)) {
                        showMessage("请扫正确的订单码");
                        return;
                    }
                } else {
                    QRcodeRequest request = new QRcodeRequest();
                    request.setQRCode(scanBean.getCode());
                    getCode(request);
                }

            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        tvAdd.setScanCallBack(null);
    }

    public void getCode(QRcodeRequest request) {
        NetUtils.geApi().scanTheQRCodeToVerify(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseAppEntity<ScanResultBean>>() {
                    @Override
                    public void accept(BaseAppEntity<ScanResultBean> stringBaseAppEntity) throws Exception {
                        if (!stringBaseAppEntity.getCode().equals("200")) {
                            ToastUtils.showToast(mContext, stringBaseAppEntity.getMessage());
                            return;
                        }
                        if (stringBaseAppEntity.getData().getType().equals("KW")) {
                            tvContainer.setText(stringBaseAppEntity.getData().getCode());
                            presenter.getWholePalletInfo(stringBaseAppEntity.getData().getCode(), stringBaseAppEntity.getData().getCode(), "10", SharedPreferencesUtil.getInstance().getString(StringKey.STORAGEBIN, ""));
                        } else {
                            ToastUtils.showToast(mContext, "请扫正确的条形码");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.showToast(mContext, throwable.getMessage());
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调
                images = PictureSelector.obtainMultipleResult(data);
                presenter.upload(images.get(0).getCompressPath());
            }
        }
    }

    @Override
    public void getData() {
        // taskResultId = getIntent().getExtras().getString("taskResultId");
    }


    @OnClick({R.id.tv_back_storage})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_back_storage:
                if (TextUtils.isEmpty(tvContainer.getText().toString())) {
                    showMessage("接驳库位不能为空！");
                    return;
                }
                AffirmDialog dialog = new AffirmDialog(mContext, new AffirmDialog.OnConfrim() {
                    @Override
                    public void onConfrim() {
                        presenter.countBackConfirm(tvContainer.getText().toString());
                    }
                });
                dialog.show("确认要回库吗");
                break;
        }
    }

    @OnClick({R.id.tv_inverntory})
    public void onViewClicked1(View view) {
        switch (view.getId()) {

            case R.id.tv_inverntory:
                if (TextUtils.isEmpty(taskResultId)) {
                    showMessage("请先扫订单码！");
                    return;
                }
                InventoryConfirmRequst requst = new InventoryConfirmRequst();
                requst.setTaskResultId(taskResultId);
                requst.setActualStockNum(etActualStockNum.getText().toString());
                try {
                    requst.setPic1Address(imageBeans.get(0).getPath());
                    requst.setPic2Address(imageBeans.get(1).getPath());
                    requst.setPic3Address(imageBeans.get(2).getPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                AffirmDialog dialog = new AffirmDialog(mContext, new AffirmDialog.OnConfrim() {
                    @Override
                    public void onConfrim() {
                        presenter.wholePalletInventoryConfirm(requst);
                    }
                });
                dialog.show("确认要盘点吗");

                break;
        }
    }

    @Override
    public void setImageEntity(ImageEntity imageEntity) {
        ImageBean imageBean = new ImageBean(imageEntity.getUrl());
        imageBeans.add(imageBean);
        if (imageBeans.size() == 4) {
            imageBeans.remove(0);
        }
        imageAdapter.notifyDataSetChanged();
    }


    WholePalletInfoBean wholePalletInfoBean;

    @Override
    public void setData(WholePalletInfoBean bean) {
        this.wholePalletInfoBean = bean;
        checkingAdapter.setNewInstance(bean.getDetails());
        if (bean.getBackButton().equals("10")) {
            tvBackStorage.setVisibility(View.GONE);
            tvInverntory.setVisibility(View.VISIBLE);
        } else {
            tvBackStorage.setVisibility(View.VISIBLE);
            tvInverntory.setVisibility(View.GONE);
        }
        /*tvArticleId.setText(bean.getArticleId());
        tvArticleName.setText(bean.getArticleName());
        tvProductModel.setText(bean.getProductModel());
        tvStorageBin.setText(bean.getStorageBinId());
        tvEntryNo.setText(bean.getEntryNo());
        tvThirdOrderNo.setText(bean.getThirdOrderNo());
        tvStockNum.setText(bean.getStockNum() + bean.getUnit());*/
    }

    @Override
    public void onSuccess() {
        this.wholePalletInfoBean = null;
        //EventBus.getDefault().post(new ContainerEvent(tvContainer.getText().toString()));
        tvArticleId.setText("");
        tvArticleName.setText("");
        tvModel.setText("");
        tvGrade.setText("");
        taskResultId = "";
        tvStorageBin.setText("");
        tvEntryNo.setText("");
        tvThirdOrderNo.setText("");
        tvStockNum.setText("");
        imageBeans.clear();
        imageBeans.add(0, new ImageBean(""));
        imageAdapter.notifyDataSetChanged();
        etActualStockNum.setText("");
        etActualStockNum.clearFocus();
        presenter.getWholePalletInfo(tvContainer.getText().toString(), "", "10", SharedPreferencesUtil.getInstance().getString(StringKey.STORAGEBIN, ""));
        //EventBus.getDefault().post(new TabEvent(2));

    }

    @Override
    public void onBackSuccess() {
        tvContainer.setText("");
        checkingAdapter.setNewInstance(new ArrayList<>());
        tvArticleId.setText("");
        tvArticleName.setText("");
        tvModel.setText("");
        tvGrade.setText("");
        taskResultId = "";
        tvStorageBin.setText("");
        tvEntryNo.setText("");
        tvThirdOrderNo.setText("");
        tvStockNum.setText("");
        imageBeans.clear();
        imageBeans.add(0, new ImageBean(""));
        imageAdapter.notifyDataSetChanged();
        etActualStockNum.setText("");
        etActualStockNum.clearFocus();
        tvBackStorage.setVisibility(View.GONE);
        tvInverntory.setVisibility(View.GONE);
    }

    @OnClick(R.id.tv_detail)
    public void onViewClicked() {
        if (TextUtils.isEmpty(tvEntryNo.getText().toString())) {
            showMessage("请先扫生产订单码");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("order", tvEntryNo.getText().toString());
        startIntent(AppActivityKey.ORDERDETAILACTIVITY, bundle);
    }
}
